package com.thiswhyme.common.utils.codec;

import com.thiswhyme.common.utils.CommonStringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author thiswhyme
 * @description 签名参数内容工具
 * @date 2021/9/12
 */
public class SignContentUtils {

    /**
     * 获取签名参数内容
     * @param params
     * @return
     */
    public static String getSignContent(Map<String, ?> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder content = new StringBuilder();
        int index = 0;
        for (String key : keys) {
            String value = String.valueOf(params.get(key));
            if (CommonStringUtils.areNotEmpty(key, value)) {
                content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                index++;
            }
        }
        return content.toString();
    }

    /**
     * 获取验签参数内容
     * @param params
     * @return
     */
    public static String getSignCheckContent(Map<String, ?> params) {
        if (params == null) {
            return null;
        }

        params.remove("sign");
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = String.valueOf(params.get(key));
            content.append(i == 0 ? "" : "&").append(key).append("=").append(value);
        }
        return content.toString();
    }
}
